package com.aluvfy.bank.web;

import com.aluvfy.bank.Exceptions.MonyNoEnough;
import com.aluvfy.bank.Exceptions.TransferException;
import com.aluvfy.bank.service.AccountService;
import com.aluvfy.bank.service.AccountServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author: aluvfy
 * @description:
 * @date: 2024/11/21 16:17
 */
@WebServlet("/transfer")
public class AccountServlet extends HttpServlet {

    //为了让这个对象在其他方法中也可以使用，声明为实例变量
    private AccountService accountService = new AccountServiceImp();
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //获取表单数据
        String fromActno = request.getParameter("fromActno");
        String toActno = request.getParameter("toActno");
        double money = Double.parseDouble(request.getParameter("money"));
        try {
            //调用service的业务方法完成转账（调业务层）
            accountService.transfer(fromActno, toActno, money);
            //程序能走到这里表示转账一定成功了
            //调用View完成视图结果
            response.sendRedirect(request.getContextPath() + "/success.html");
        } catch (MonyNoEnough e) {
            response.sendRedirect(request.getContextPath() + "/error1.html");
        } catch (TransferException e) {
            response.sendRedirect(request.getContextPath() + "/error2.html");
        } catch (Exception e) {
            response.sendRedirect(request.getContextPath() + "/error2.html");
        }

    }
}
